#include "kerkmeans_def.hpp"
#include "kerkmeans_impl.hpp"

//Features as per Andres' WACV paper

inline
opt_feat::opt_feat(const std::string in_path, 
		   const std::string in_actionNames,  
		   const std::string in_feat_path,
		   const int in_col, 
		   const int in_row)
:path(in_path), actionNames(in_actionNames), feat_path(in_feat_path), col(in_col), row(in_row), n_samples_tr(17), n_samples_te(8)
{
  THRESH = 0.000001;
  Ncent = 8;
}


inline
void
opt_feat::training()
{
  //calc_features();//Ya las calcule
  clustering();
  
}


inline
void
opt_feat::testing(){
  
  double acc = 0; //accuracy
  int num_samples;
  num_samples = n_samples_te; 
    
  std::stringstream tmp_ss;
  tmp_ss << path << actionNames;
  actions.load(tmp_ss.str());
  double n_test = actions.n_rows*num_samples;
  
  double n_train = n_samples_tr*actions.n_rows;
  
   
  
  //no sabemos el numero total de cov por videos
  //Sirve para H2
  //rowvec dist_stein;
  //rowvec lab_train;
  //dist_stein.set_size(n_train*N_cent); // each video has N_Cent cov matrices
  //lab_train.set_size(n_train*N_cent); 
  
  // usar <vector> moved below
  //std::vector<double> dist_stein;
  //std::vector<double> lab_train;
  
  mat log_covMte;
  mat log_covMtr;
  
  
  for (uword act = 0 ; act < actions.n_rows; ++act) {
    
    cout << actions(act) << endl;
    std::stringstream tmp_ss2;
    tmp_ss2 << path << actions(act)<<"/test/test_list.txt";
    //cout << tmp_ss2.str()<< endl;
    //getchar();
    videos.load(tmp_ss2.str()); 
    
    for (uword vi = 0; vi <videos.n_rows; ++vi ){ 
      covs.clear();
      num_covs = 0;
      
      //cout << "Size: " << covs.size() << endl;
      std::stringstream tmp_ss3;
      tmp_ss3 << path << actions(act)<<"/test/"<<  videos(vi);
      cov_features(tmp_ss3.str()); //covs is calculated here
      
      
      //CLUSTER COVs matrices
       field<mat> cluster_cov = clustering_testing();
      
      
      //field<mat> full_covs_test = km.get_covs();
      vec count = zeros<vec>(actions.n_rows);
      
      for (uword i = 0; i < Ncent; ++i) // Each covariance matrix per video testing_vi is classified
      {
	
	mat cov_i_te = cluster_cov(i);
	
	std::vector<double> dist_stein;
	std::vector<double> lab_train;
	
	for (uword act_tr = 0 ; act_tr < actions.n_rows; ++act_tr) {
	  for (uword tr = 0; tr <n_samples_tr; ++tr ){ 
	    
	    std::stringstream tmp_full;
	    tmp_full << feat_path << "cluster_cov/"<< Ncent << "_CovFeatures_" << actions(act_tr) << "_"<< tr+1; // vi Starting at 1
	    //cout << "Comparing with: " << tmp_full.str() << endl;
	    field<mat> full_covs_tr;
	    full_covs_tr.load(tmp_full.str());
	    //out << " " <<full_covs_tr.n_rows << " ";
	    
	    for (uword k = 0; k < full_covs_tr.n_rows; ++k){
	      //cout << "i: " << i << ". j: " << j << ". k: " << k << endl;
	      mat cov_i_tr = full_covs_tr(k);
	      
	      
	      double det_op1 = det( diagmat( (cov_i_tr + cov_i_te)/2 ) );
	      double det_op2 = det( diagmat( ( cov_i_tr%cov_i_te ) ) );
	      double dist = sqrt ( log( det_op1 ) -0.5*log( det_op2 ) );
	      dist_stein.push_back(dist);
	      lab_train.push_back(act_tr);
	    }
	    
	  }
	  
	}
	//getchar();
	rowvec dist_stein_arma = conv_to<rowvec>::from(dist_stein);
	rowvec lab_train_arma  = conv_to<rowvec>::from(lab_train);
	//lab_train_arma.print("labels");
	//lab_train.print("labels training:");
	//getchar();
	
	//lab_train.print("lab_train");
	uword  index;
	double min_val = dist_stein_arma.min(index);
	//dist.print("dist: ");
	//cout << "index = " << index << endl;
	uword  est_class = lab_train_arma(index);
	count(est_class)++;
	
	
      }
      
      uword  index_video;
      double max_val = count.max(index_video);
      //count.t().print("count:");
      cout << "This video is " << actions(act) << " and was classified as class: " << actions(index_video );
      //getchar();
      if (index_video == act)
      {
	acc++;
	cout << ". Good: " << acc;
      }
      
      cout << endl;
    }
  }
  cout << "Performance: " << acc*100/n_test << " %" << endl;
}



inline
void 
opt_feat::calc_features() // Este solo sirve para entreamiento, no para validacion. 
{
  cout <<"Calculating covariance descriptor per video"<< endl;
  int num_samples;
  
  std::stringstream tmp_ss;
  tmp_ss << path << actionNames;
  actions.load(tmp_ss.str());
  //actions.print("All actions");
  
  
  
  for (uword act = 0 ; act < actions.n_rows; ++act) {
    
    std::stringstream tmp_ss2;
    tmp_ss2 << path << actions(act)<<"/train/train_list.txt";    
    //cout << tmp_ss2.str()<< endl;
    //getchar();
    videos.load(tmp_ss2.str());
    //videos.print("All videos");
    
    
    for (uword vi = 0; vi <videos.n_rows; ++vi ){ 
      covs.clear();
      num_covs = 0;
      std::stringstream tmp_ss3;
      tmp_ss3 << path << actions(act)<<"/train/"<<  videos(vi);
      cov_features(tmp_ss3.str()); //covs is calculated here
      std::stringstream tmp_ss4;
      tmp_ss4 << feat_path << "train" << "/CovFeatures_" << actions(act) << "_"<< vi+1; // vi Starting at 1
      cout << "Saving in" << tmp_ss4.str() << "num_covs: " << num_covs << endl;;
      
      saving(tmp_ss4.str()); // saving cov descriptors per video.
      
    }
  }
}


inline 
void
opt_feat::cov_features(std::string one_video)//covariance features per video
{
  
  cv::VideoCapture capVideo(one_video);
  //cout << one_video << endl;
  //double fps = capVideo.get(CV_CAP_PROP_FPS); //get the frames per seconds of the video
  //cout << "Frame per seconds : " << fps << endl;
  
  //cv::namedWindow("MyVideo",CV_WINDOW_AUTOSIZE); //create a window called "MyVideo"
  
  //double frmcount = capVideo.get(CV_CAP_PROP_FRAME_COUNT);
  //cout << "# of frames is: " << frmcount << endl;
  
  if( !capVideo.isOpened() )
  {
    cout << "Video couldn't be opened" << endl;
    return;
  }
  
  cv::Mat prevgray, gray, flow, cflow, frame, prevflow;
  cv::Mat ixMat, iyMat, ixxMat, iyyMat;
  //cv::namedWindow("My Video", 1);
  running_stat_vec<vec> stats_video(true);
  //cout << "Frame: ";
  int t = 0;
  int N_vectors = 0;
  int n_segm = 0;
  for(;;){
    
    
    //capVideo >> frame;
    
    bool bSuccess = capVideo.read(frame); // read a new frame from video
    
    if (!bSuccess) //if not success, break loop
      	{
	  //cout << "Cannot read the frame from video file" << endl;
	  break;
	}
	t++;
    cv::cvtColor(frame, gray, CV_BGR2GRAY);
    
    if( prevgray.data )
    {
      //cout << "Cuando entra aca?? en t= " << t << endl;
      cv::calcOpticalFlowFarneback(prevgray, 
				   gray, 
				   flow, 
				   0.5, //pyr_scale
				   3,   //levels
				   9,   //winsize
				   1,   //iterations
				   5,   //poly_n
				   1.1, //poly_sigma
				   0);  //flags
      //cv::calcOpticalFlowFarneback(bl_currentImg, bl_nextImg, flow, 0.5,  3, 5, 3, 5, 1.2, 0); 
      //cv::cvtColor(prevgray, cflow, CV_GRAY2BGR);
      //drawOptFlowMap(flow, cflow, 8, 1.5, CV_RGB(0, 255, 0));
      //cv::imshow("flow", cflow);
      
      
      cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1);
      cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1);
      cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1);
      cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1);
      
      float  ux = 0, uy = 0, vx = 0,  vy = 0;
      float u, v;
      //cout << "Llega a ciclo de Pixels???" << endl;
      //cout << "col: " << col << "- row " << row << endl;
      
      //printing frame number
      //cout << " " << t;
      if( prevflow.data )
      {
	
	if (n_segm == 4) // when I have 5 (0,1,2,3,4) consecutive frames I calculate one covariance descriptor
	{
	  //cout << "n_segm= " << n_segm;
	  //cout << "N_vectors = " << N_vectors << endl;
	  mat cov = stats_video.cov();
	  
	  // I discard the segments with a number of pixels below 5% of all the possible feature vectors in one frame
	  if (N_vectors > col*row/20) 
	  {
	    //cout << "Aqui 0 ";
	    //Following Mehrtash suggestions as per email dated June26th 2014
	    //cov.print("cov");
	    
	    cov = 0.5*(cov + cov.t());
	    //cout << "Aqui 0.5 ";
	    vec D;
	    mat V;
	    eig_sym(D, V, cov);
	    uvec q1 = find(D < THRESH);
	    //cout << "Aqui 1 ";
	    if (q1.n_elem>0)
	    {
	      for (uword pos = 0; pos < q1.n_elem; ++pos)
	      {
		D( q1(pos) ) = THRESH;
	      }
	      //cout << "***cov_hat***" << endl;
	      cov = V*diagmat(D)*V.t();  //
	    }  
	    //cout << "Aqui 2 ";
	    
	    covs.push_back(cov);
	    num_covs++;
	    //cout << num_covs << " covariance descriptors per current video" << endl;
	    
	  }
	  else{
	    //cout << "      Covariance discarded." << endl;
	  }
	  
	  //cout << "Aqui 3 ";
	  stats_video.reset();
	  N_vectors = 0;
	  n_segm = 0;
	  
	  //cout << " num_covs= " << num_covs << ". Label is: " << act <<endl;
	  
	}
	
	
	for (uword x = 0 ; x < col ; ++x ){
	  for (uword y = 0 ; y < row ; ++y ) {
	    
	    vec features_one_pixel(15);
	    u = flow.at<cv::Vec2f>(y, x)[0];
	    v = flow.at<cv::Vec2f>(y, x)[1];
	    
	    //cout << "x= " << x << " - y= " << y << endl;
	    // x grad
	    //cout << " x y grad" << endl;
	    float ix = ixMat.at<float>(y, x);
	    //cout << " y grad" << endl;
	    float iy = iyMat.at<float>(y, x);
	    
	    // grad direction &  grad magnitude
	    //cout << "grad direction &  grad magnitude" << endl;
	    float gd = std::atan2(std::abs(iy), std::abs(ix));
	    float gm = std::sqrt(ix * ix + iy * iy);
	    
	    // x second grad
	    //cout << "x y  second grad " << endl;
	    float ixx = ixxMat.at<float>(y, x);
	    // y second grad
	    float iyy = iyyMat.at<float>(y, x);
	    
	    //du/dt
	    float ut = u - prevflow.at<cv::Vec2f>(y, x)[0];
	    // dv/dt
	    float vt = v - prevflow.at<cv::Vec2f>(y, x)[1];
	    
	    //// divergence &  vorticity
	    //cout << "divergence &  vorticity" << endl;
	    if (x>0 && y>0 )
	    {
	      ux = u - flow.at<cv::Vec2f>(y, x - 1)[0];
	      uy = u - flow.at<cv::Vec2f>(y - 1, x)[0];
	      vx = v - flow.at<cv::Vec2f>(y, x - 1)[1];
	      vy = v - flow.at<cv::Vec2f>(y - 1, x)[1];
	    }
	    //int x_submat = x + rec.x;
	    //int y_submat = y + rec.y;
	    //cout << x_submat << "&" << y_submat << endl;
	    
	    
	    
	    features_one_pixel  << x << y << t << abs(ix) << abs(iy) << abs(ixx) 
	    << abs(iyy) << gm << gd <<  u << v << abs(ut) 
	    << abs(ut) << (ux - vy)  << (vx - uy);
	    //features_one_pixel.t().print("Features Current Pixel: ");
	    //getchar();
	    
	    
	    if (!is_finite( features_one_pixel ) )
	    {
	      cout << "It's not FINITE... continue???" << endl;
	      getchar(); 
	    }
	    
	    // Plotting Moving pixels
	    //cout << " " << gm;
	    if (gm>40) // Empirically set to 40
			    {
			      frame.at<cv::Vec3b>(y,x)[0] = 0;
			      frame.at<cv::Vec3b>(y,x)[1] = 0;
			      frame.at<cv::Vec3b>(y,x)[2] = 255;
			      stats_video(features_one_pixel);
			      N_vectors++;
			      
			    }
			    //cout << stats_video.cov() << endl;
	    //cout << stats_video.mean() << endl;
	  }
	}
	n_segm++;
	//cout << n_segm << endl;
	//cv::imshow("action", frame);
	//cv::waitKey(50);
      }
    }
    if(cv::waitKey(30)>=0)
      break;
    //cout << " t: " <<t;
      std::swap(prevgray, gray);
      std::swap(prevflow, flow);//aca esta el problema.... cuando hay flow????
      
  } 
}


//clustering on testing set
//Lo hago asi devolviendo field<mat> para no confundirme
inline
field<mat> 
opt_feat::clustering_testing( )
{

    field<mat> riemann_points;
    riemann_points.set_size(num_covs); // Column1: Cov Matrices
  
  for (uword i=0; i<num_covs; ++i)
  {
    
    riemann_points(i,0) = covs.at(i);
  }

  
      int N_points = riemann_points.n_rows;
      mat K = zeros(N_points, N_points);
      double sig = 0.5; // Sigma
      //double s2 = s*dim;
      double detXpY; //plus
      double detXtY; //times
      double S;
      //mat tmp;
      for (uword i = 0; i < N_points ;  ++i)
      {
	for (uword j = i; j < N_points ;  ++j)
	{
	  detXpY = det( (riemann_points(i) + riemann_points(j))/2 );
	  detXtY = det( riemann_points(i)*riemann_points(j) );
	  
	  S = log( detXpY  ) - log(detXtY)/2;
	  K(i,j) = exp(-sig*S);
	  //cout << "K(i,j): " << K(i,j) << endl;
	  //getchar();
	}
      }
      
      K = symmatu(K);
      //K.print("K:");
      ///Kernel Kmeans 
     
      kerkmeans kkmeans(K, Ncent);
      kkmeans.calc(10);
      //kkmeans.get_partitions();
      vec indices = kkmeans.get_indices();
      field<mat> cluster_cov(Ncent);
      
      for (uword n=0; n< Ncent; ++n)
      {
      cluster_cov(n) = riemann_points(indices(n));
      }
      
      return cluster_cov;
      

}





//clustering on training set
inline
void
opt_feat::clustering( )
{
  
  cout << "Calculating Stein Kernel Faster?? " << endl;  
  
  std::stringstream tmp_ss;
  tmp_ss << path << actionNames;
  actions.load(tmp_ss.str());
  int num_samples;
  num_samples = n_samples_tr; 
  
  
  for (uword act_tr = 0 ; act_tr < actions.n_rows; ++act_tr) {
    for (uword tr = 0; tr <n_samples_tr; ++tr ){ 
      
      std::stringstream tmp_cov;
      tmp_cov<< feat_path << "train" << "/CovFeatures_" << actions(act_tr) << "_"<< tr+1; // vi Starting at 1
      cout << "Loading " << tmp_cov.str() << endl;
      field<mat> riemann_points;
      riemann_points.load(tmp_cov.str());
      int N_points = riemann_points.n_rows;
      mat K = zeros(N_points, N_points);
      double sig = 0.5; // Sigma
      //double s2 = s*dim;
      double detXpY; //plus
      double detXtY; //times
      double S;
      //mat tmp;
      for (uword i = 0; i < N_points ;  ++i)
      {
	for (uword j = i; j < N_points ;  ++j)
	{
	  detXpY = det( (riemann_points(i) + riemann_points(j))/2 );
	  detXtY = det( riemann_points(i)*riemann_points(j) );
	  
	  S = log( detXpY  ) - log(detXtY)/2;
	  K(i,j) = exp(-sig*S);
	  //cout << "K(i,j): " << K(i,j) << endl;
	  //getchar();
	}
      }
      
      K = symmatu(K);
      //K.print("K:");
      ///Kernel Kmeans 
     
      kerkmeans kkmeans(K, Ncent);
      kkmeans.calc(10);
      //kkmeans.get_partitions();
      vec indices = kkmeans.get_indices();
      field<mat> cluster_cov(Ncent);
      
      for (uword n=0; n< Ncent; ++n)
      {
      cluster_cov(n) = riemann_points(indices(n));
      }
      
      std::stringstream tmp_cov2;
      tmp_cov2 << feat_path << "cluster_cov/" << Ncent<<"_CovFeatures_" << actions(act_tr) << "_"<< tr+1; // vi Starting at 1
      cluster_cov.save( tmp_cov2.str() );
    }
  }
}



inline 
void
opt_feat::saving(std::string cov_feat_name)
{
  field<mat> features;
  features.set_size(num_covs); // Column1: Cov Matrices
  
  for (uword i=0; i<num_covs; ++i)
  {
    
    features(i,0) = covs.at(i);
  }
  
  
  features.save(cov_feat_name);
  
}
